<template>
  <view class="content min-h-screen pb-4">
    <NavigationBar title="预约" />
    <!-- 医师列表 -->
    <view class="px-5 pt-[28rpx]">
      <!-- 医师卡片 -->
      <view
        v-for="(doctor, index) in doctorList"
        :key="index"
        class="bg-white rounded-lg mb-3 py-[38rpx] px-[20rpx] flex items-center justify-between"
      >
        <view class="flex items-center">
          <!-- 医师头像 -->
          <image
            :src="doctor.avatar"
            mode="aspectFill"
            class="w-[135rpx] h-[135rpx] rounded-full"
          ></image>

          <view class="ml-4">
            <!-- 医师名称 -->
            <view class="text-base text-[#252523] font-bold">
              {{ doctor.name }}
            </view>
            <!-- 服务项目图片 -->
            <view class="flex space-x-2 mt-2">
              <image
                v-for="(serviceImg, sIndex) in doctor.serviceImages"
                :key="sIndex"
                :src="serviceImg"
                class="w-[80rpx] h-[80rpx] rounded-[16rpx]"
              ></image>
            </view>
          </view>
        </view>

        <!-- 预约按钮 -->
        <view
          :class="['reservationbtn', doctor.status == 1 ? 'disabled' : '']"
          @click="
            doctor.status === 0 ? openTimeSelector(doctor.id.toString()) : ''
          "
          >{{ "预约" }}</view
        >
      </view>
    </view>
  </view>

  <!-- 时间选择弹窗 -->
  <view
    v-if="showTimeSelector"
    class="fixed inset-0 bg-black bg-opacity-50 z-40"
    @click="closeTimeSelector"
  ></view>
  <view
    v-if="showTimeSelector"
    class="w-[670rpx] h-[760rpx] fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white rounded-[20rpx] flex flex-col z-50 shadow-lg"
  >
    <!-- 弹窗标题 -->
    <view
      class="flex justify-center relative py-[20rpx] border-b border-gray-100"
    >
      <text class="text-[36rpx] font-semibold text-[#333333]">选择时间</text>

      <text
        class="absolute right-[30rpx] top-[20rpx] text-gray-500"
        @click="closeTimeSelector"
      >
        <img src="@/static/home/close.png" alt="" class="w-[38rpx] h-[38rpx]" />
      </text>
    </view>

    <!-- 弹窗内容区域（可滚动） -->
    <scroll-view class="flex-1 p-[30rpx]" scroll-y>
      <!-- 日期选择 -->
      <view class="mb-[30rpx]">
        <view
          class="flex items-center justify-between border border-[#979797] rounded-[10rpx] pt-[18rpx] pb-[14rpx] pl-[20rpx] pr-[25rpx] mt-[10rpx]"
        >
          预约时间：
          <uni-datetime-picker
            type="date"
            :border="false"
            :start="getCurrentDate()"
            v-model="single"
            @change="handleDateChange"
          />
        </view>
      </view>

      <!-- 时间选择 -->
      <view class="mb-[20rpx]" v-if="single">
        <view
          class="flex items-center justify-between border border-[#979797] rounded-[10rpx] pt-[18rpx] pb-[14rpx] pl-[20rpx] pr-[25rpx] mt-[10rpx]"
          @click="openTimePicker"
        >
          <text>入馆时间：</text>
          <text class="text-gray-600">{{ selectedTime || "请选择时间" }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 确认按钮（固定在底部） -->
    <view class="px-[30rpx] py-[20rpx] border-t border-gray-100">
      <view
        :class="[
          'w-full h-[90rpx] rounded-[44rpx] flex items-center justify-center text-white text-[32rpx] font-medium',
          canConfirm ? 'btnLinearGradient' : 'bg-gray-300',
        ]"
        @click="confirmSelection"
        >确定</view
      >
    </view>
  </view>

  <!-- 时间选择弹窗 -->
  <view
    v-if="showTimePicker"
    class="fixed inset-0 bg-black bg-opacity-50 z-40"
    @click="closeTimePicker"
  ></view>
  <view
    v-if="showTimePicker"
    class="w-[600rpx] h-[700rpx] fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white rounded-[20rpx] flex flex-col z-50 shadow-lg"
  >
    <!-- 弹窗标题 -->
    <view
      class="flex justify-center relative py-[30rpx] border-b border-gray-100"
    >
      <text class="text-[36rpx] font-semibold text-[#333333]"
        >选择入馆时间</text
      >
      <text
        class="absolute right-[30rpx] top-[30rpx] text-gray-500"
        @click="closeTimePicker"
      >
        <img src="@/static/home/close.png" alt="" class="w-[38rpx] h-[38rpx]" />
      </text>
    </view>

    <!-- 时间选择区域 -->
    <scroll-view class="flex-1 p-[30rpx]" scroll-y>
      <view class="mb-[20rpx]">
        <text class="text-[28rpx] text-[#666666] mb-[20rpx] block"
          >请选择入馆时间（9:30-20:00）</text
        >
        <view class="grid grid-cols-3 gap-[15rpx]">
          <view
            v-for="(time, index) in timeOptions"
            :key="index"
            class="h-[120rpx] border border-solid rounded-[12rpx] flex flex-col items-center justify-center cursor-pointer relative overflow-hidden"
            :class="
              selectedTime === time
                ? 'border-[#d7a56b] bg-[#FFF5E6]'
                : 'border-gray-200 bg-white'
            "
            @click="selectTime(time)"
          >
            <text
              :class="
                selectedTime === time ? 'text-[#AF6C31]' : 'text-[#666666]'
              "
              class="text-[26rpx] font-medium"
              >{{ time }}</text
            >
            <text
              :class="
                selectedTime === time ? 'text-[#AF6C31]' : 'text-[#999999]'
              "
              class="text-[22rpx] mt-[5rpx]"
              >{{ getTimePeriod(time) }}</text
            >
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 确认按钮（固定在底部） -->
    <view class="px-[30rpx] py-[20rpx] border-t border-gray-100">
      <view
        :class="[
          'w-full h-[90rpx] rounded-[44rpx] flex items-center justify-center text-white text-[32rpx] font-medium',
          selectedTime ? 'btnLinearGradient' : 'bg-gray-300',
        ]"
        @click="confirmTimeSelection"
        >确定</view
      >
    </view>
  </view>
</template>

<script setup lang="ts">
import NavigationBar from "@/components/navigationBar/index.vue";
import {
  getDoctorAvailableTime,
  type DoctorAvailableTimeResponseData,
} from "@/api/goods";
import { createOrder } from "@/api/home";
import { ref, computed } from "vue";
import { getDoctor, type DoctorResponseData } from "@/api/home";
import { onLoad } from "@dcloudio/uni-app";
const queryId = ref(0);
// 医师列表
const doctorList = ref<
  Array<DoctorResponseData & { serviceImages?: string[] }>
>([]);

// 选中的医师信息
const selectedDoctor = ref<DoctorResponseData | null>(null);

// 时间选择弹窗相关变量
const showTimeSelector = ref(false);
const showTimePicker = ref(false); // 时间选择弹窗显示状态
const single = ref<string>(""); // 选中的日期
const selectedTime = ref<string>(""); // 选中的时间
const timeOptions = ref<string[]>([]); // 时间选项列表
const doctorId = ref(""); // 商品id
const queryPrice = ref(0); // 商品价格
const queryIsProduct = ref(0); // 是否是产品 0产品 1项目
// 检查是否可以点击确认按钮
const canConfirm = computed(() => {
  return single.value && selectedTime.value;
});
const queryPaymentType = ref(0); // 支付类型 0现金 1积分

// 获取当前日期，格式为 YYYY-MM-DD
const getCurrentDate = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const day = String(today.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

onLoad((option: any) => {
  queryId.value = option.id;
  queryPrice.value = option.price;
  queryIsProduct.value = option.isProduct;
  queryPaymentType.value = option.paymentType;
  getDoctor().then((res) => {
    doctorList.value = res.data.map((item: DoctorResponseData) => {
      return {
        ...item,
        serviceImages: item.expertise ? item.expertise.split(",") : [],
      };
    });
    console.log(doctorList.value, "doctorList.value");
  });
});

// 打开时间选择器
const openTimePicker = () => {
  const timeOptions = generateTimeOptions();
  uni.showActionSheet({
    itemList: timeOptions,
    success: (res) => {
      selectedTime.value = timeOptions[res.tapIndex];
      console.log("选择的时间:", selectedTime.value);
    },
  });
};

// 生成时间选项
const generateTimeOptions = () => {
  const options = [];
  const startHour = 9;
  const startMinute = 30;
  const endHour = 20;
  const endMinute = 0;

  let currentHour = startHour;
  let currentMinute = startMinute;

  while (
    currentHour < endHour ||
    (currentHour === endHour && currentMinute <= endMinute)
  ) {
    const timeString = `${String(currentHour).padStart(2, "0")}:${String(currentMinute).padStart(2, "0")}`;
    options.push(timeString);

    // 增加30分钟
    currentMinute += 30;
    if (currentMinute >= 60) {
      currentMinute = 0;
      currentHour++;
    }
  }

  return options;
};

// 打开时间选择器
const openTimeSelector = (id: string) => {
  showTimeSelector.value = true;
  // 重置选择状态
  single.value = "";
  selectedTime.value = "";
  doctorId.value = id;

  // 保存当前选中的医师信息
  const doctor = doctorList.value.find((d) => d.id.toString() === id);
  if (doctor) {
    selectedDoctor.value = doctor;
  }
};

// 关闭时间选择器
const closeTimeSelector = () => {
  showTimeSelector.value = false;
};

const handleDateChange = (e: any) => {
  console.log("handleDateChange事件:", e);
  single.value = e;
  // 选择日期后重置时间选择
  selectedTime.value = "";
};

// 创建订单
const handleCreateOrder = () => {
  // 判断是上午还是下午
  const hour = parseInt(selectedTime.value.split(":")[0]);
  const isMorning = hour < 12 ? 0 : 1; // 0表示上午，1表示下午

  const data = {
    userId: uni.getStorageSync("userInfo").id,
    projectId: queryId.value,
    paymentType: queryPaymentType.value, // 默认为null   0-现金支付，1-积分支付
    doctorId: selectedDoctor.value?.id || 0,
    totalPrice: queryPrice.value, // 订单总价
    appointmentDate: single.value, // 预约日期
    appointmentTime: selectedTime.value + ":00", // 添加秒数
    isMorning: isMorning, // 是否是上午 0 是 1否
  };

  createOrder(data).then((res) => {
    if (res.code == 200) {
      uni.navigateTo({
        url:
          "/pages/home/successfully?id=" +
          res.data.masterId +
          "&isProduct=" +
          queryIsProduct.value,
      });
    }
  });
};
// 确认选择
const confirmSelection = async () => {
  if (!canConfirm.value) {
    uni.showToast({
      title: "请选择预约日期和入馆时间",
      icon: "none",
    });
    return;
  }
  // 获取选中的医师和时间
  const doctorName = selectedDoctor.value?.name || "";

  uni.showToast({
    title: `已预约${doctorName}医师 ${single.value} ${selectedTime.value}`,
    icon: "none",
  });
  await handleCreateOrder();

  await closeTimeSelector();
};

const navigateBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="scss">
.reservationbtn {
  width: 150rpx;
  height: 60rpx;
  background: linear-gradient(270deg, #d7a56b 0%, #ebd7ac 100%, #a58c56 100%);
  border-radius: 44rpx;

  font-weight: 400;
  font-size: 30rpx;
  color: #ffffff;
  line-height: 42rpx;
  text-align: center;
  font-style: normal;
  display: flex;
  align-items: center;
  justify-content: center;
}

.disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.btnLinearGradient {
  background: linear-gradient(270deg, #d7a56b 0%, #ebd7ac 100%, #a58c56 100%);
}
</style>
